package net.zoneland.knowledge.utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;

/**
 * 请求参数获取工具类.
 */
public final class RequestUtils {

    private RequestUtils() {
    }

    /**
     * 获取请求参数.
     * @param request 请求
     * @return request请求参数
     * @throws IOException IOException
     */
    public static String getRequestString(final HttpServletRequest request) throws IOException {
        String queryString = null;
        if (StringUtils.isNotBlank(request.getQueryString())) {
            final byte[] queryStringByte = request.getQueryString().getBytes(StandardCharsets.ISO_8859_1.name());
            queryString = new String(queryStringByte, StandardCharsets.UTF_8.name());
        }
        return "queryString:" + queryString + "postBody:" + getRequestPostStr(request);
    }

    /**
     * 获取post请求参数转字符串.
     * @param request 请求
     * @return post请求参数
     * @throws IOException IOException
     */
    private static String getRequestPostStr(final HttpServletRequest request) throws IOException {
        if (HttpMethod.GET.name().equals(request.getMethod())) {
            return StringUtils.EMPTY;
        }
        byte[] buffer = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = StandardCharsets.UTF_8.name();
        }
        return new String(buffer, charEncoding);
    }

    /**
     * 获取post请求数据.
     * @param request 请求
     * @return post请求字节流
     * @throws IOException IOException
     */
    private static byte[] getRequestPostBytes(final HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 1) {
            return null;
        }
        byte[] buffer = new byte[contentLength];
        for (int i = 0; i < contentLength;) {
            int readLen = request.getInputStream().read(buffer, i, contentLength - i);
            if (readLen == -1) {
                break;
            }
            i += readLen;
        }
        return buffer;
    }

}
